import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/animation.dart';
import 'package:get/get.dart';
import 'package:rembercount/controller/authLoginController.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';



class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
  final dio = Dio(BaseOptions(
  baseUrl: const String.fromEnvironment('BASE_URL', defaultValue: "http://localhost:8080"),
));
}

class _LoginScreenState extends State<LoginScreen> with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _opacityAnimation;
  late Animation<double> _translateAnimation;
  final Authlogincontroller authlogincontroller = Get.find<Authlogincontroller>();
  // TextEditingController _emailcontroller=TextEditingController();
  // TextEditingController _passwordcontroller=TextEditingController();
  final _formKey = GlobalKey<FormState>();
 

  @override
  void initState() {
    super.initState();
    
    _controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 2),
    )..repeat(reverse: true);

    _opacityAnimation = Tween(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: Curves.easeIn,
      ),
    );

    _translateAnimation = Tween(begin: -50.0, end: 50.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: Curves.easeInOut,
      ),
    );
    authlogincontroller.emailController.text='lcz@qq.com';
    authlogincontroller.passwordController.text='12345678';
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // 动态背景层
          AnimatedBuilder(
            animation: _controller,
            builder: (context, child) {
              return Transform.translate(
                offset: Offset(_translateAnimation.value, 0),
                child: Opacity(
                  opacity: 0.05,
                  child: Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [Colors.green[300]!, Colors.blue[300]!],
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                      ),
                    ),
                  ),
                ),
              );
            },
          ),

          // 主内容层
          Padding(
            padding: EdgeInsets.all(30),
            child: Form(
              key: _formKey,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  // 标题部分
                  AnimatedText(),
                  SizedBox(height: 50),

                  // 输入框组
                  _buildInputField(
                    icon: Icons.person_outline,
                    
                    label: '邮箱',
                    validator: (value) => value!.isEmpty ? '请输入邮箱' : null,
                  ),
                  SizedBox(height: 25),
                  _buildInputField(
                    icon: Icons.lock_outline,
                    label: '密码',
                    isPassword: true,
                    validator: (value) => value!.length < 6 ? '密码至少6位' : null,
                  ),
                  SizedBox(height: 40),

                  // 登录按钮
                  ElevatedButton(
                    onPressed: _submitForm,
                    style: ElevatedButton.styleFrom(
                      padding: EdgeInsets.symmetric(vertical: 18),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(15),
                      ),
                      elevation: 5,
                      shadowColor: Colors.green.withOpacity(0.3),
                    ),
                    child: Text('登  录', 
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w600,
                        letterSpacing: 1.2
                      ),
                    ),
                  ),
                  SizedBox(height: 25),

                  // 辅助链接
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      TextButton(
                        onPressed: () {
                          Get.toNamed('/forgetPassword');
                        },
                        child: Text('忘记密码?', 
                          style: TextStyle(color: Colors.grey[600])
                        ),
                      ),
                      SizedBox(width: 20),
                      TextButton(
                        onPressed: () {
                          Get.toNamed('/register');
                        },
                        child: Text('注册账号', 
                          style: TextStyle(
                            color: Colors.green[700],
                            fontWeight: FontWeight.w600
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildInputField({
    required IconData icon,
    required String label,
    bool isPassword = false,
    required FormFieldValidator<String>? validator,
  }) {
    return TextFormField(
      obscureText: isPassword,
      controller: label=="邮箱"?authlogincontroller.emailController:authlogincontroller.passwordController,
      validator: validator,
      decoration: InputDecoration(
        labelText: label,
        prefixIcon: Icon(icon, color: Colors.grey[600]),
        contentPadding: EdgeInsets.symmetric(vertical: 18, horizontal: 20),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide.none,
        ),
        filled: true,
        fillColor: Colors.white,
        floatingLabelBehavior: FloatingLabelBehavior.auto,
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(color: Colors.green, width: 1.5),
        ),
        labelStyle: TextStyle(
          color: Colors.grey[600],
          fontSize: 16
        ),
      ),
    );
  }

  void _submitForm()async {
    widget.dio.get("/test").then((value) {
      print(value.data);
    });
    if (_formKey.currentState!.validate()) {
      // 处理登录逻辑
      var data={
        "email": authlogincontroller.emailController.text,
        "password": authlogincontroller.passwordController.text,
      };
      var r= await widget.dio.post("/login",data:data);
      if(r.data['code']==200){
        print('r.data: ${r.data}');
        if(r.data['data']['phone']==null){
 TDToast.showText('登陆成功', context: context);
        await authlogincontroller.saveLoginStatus();
        Get.toNamed("/mainpage");
        }else{
 authlogincontroller.phoneController.text = r.data['data']['phone'];
        TDToast.showText('登陆成功', context: context);
        await authlogincontroller.saveLoginStatus();
        Get.toNamed("/mainpage");
        }
        
      }else{
        TDToast.showText('登陆失败:${r.data['msg']}', context: context);
      }
    }
  }
}

class AnimatedText extends StatefulWidget {
  @override
  _AnimatedTextState createState() => _AnimatedTextState();
}

class _AnimatedTextState extends State<AnimatedText> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<Offset> _slideAnimation;
  late Animation<double> _fadeAnimation;

  @override
  void initState() {
    super.initState();
    
    _controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 800),
    )..forward();

    _slideAnimation = Tween<Offset>(
      begin: Offset(0, -0.5),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.easeOutBack,
    ));

    _fadeAnimation = Tween(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: Curves.easeIn,
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
      position: _slideAnimation,
      child: FadeTransition(
        opacity: _fadeAnimation,
        child: Column(
          children: [
            Text('Financials',
              style: TextStyle(
                fontSize: 36,
                fontWeight: FontWeight.bold,
                color: Colors.green[700],
                letterSpacing: 1.5,
              ),
            ),
            SizedBox(height: 10),
            Text('智慧财务管理平台',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
                letterSpacing: 1.2
              ),
            )
          ],
        ),
      ),
    );
  }
}